<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList(1)">
      <el-form-item>
        <el-input v-model="dataForm.keyword.key" placeholder="请输入活动名称搜索" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList(1)">查询</el-button>
        <el-button v-if="isAuth('picbook:pbexchagegroup:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('picbook:pbexchagegroup:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="兑换活动名称">
      </el-table-column>
      <el-table-column
        prop="exchangeType"
        header-align="center"
        align="center"
        label="兑换类型">
      </el-table-column>
      <el-table-column
        prop="exchangeDays"
        header-align="center"
        align="center"
        label="兑换天数">
      </el-table-column>
      <el-table-column
        prop="codeCount"
        header-align="center"
        align="center"
        label="兑换码总数">
      </el-table-column>
      <el-table-column
        prop="startTime"
        header-align="center"
        align="center"
        label="兑换券生效时间">
      </el-table-column>
      <el-table-column
        prop="endTime"
        header-align="center"
        align="center"
        label="兑换券过期时间">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="状态">
        <template slot-scope="scope">
          <div v-if="scope.row.status === 1">上架</div>
          <div v-if="scope.row.status === 0">下架</div>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
          <el-button type="text" size="small" @click="onOroffHandle(scope.row.id, scope.row.status)" v-if="scope.row.status === 1">下架</el-button>
          <el-button type="text" size="small" @click="onOroffHandle(scope.row.id, scope.row.status)" v-if="scope.row.status === 0">上架</el-button>
          <el-button type="text" size="small" @click="downloadHandle(scope.row.id)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './pbexchagegroup-add-or-update'
  export default {
    data () {
      return {
        dataForm: {
          keyword: {
            key: ''
            // ,pId: ''
          }
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList (formSearch) {
        // 搜索框来源
        if (formSearch === 1) {
          this.pageIndex = 1
        }
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/picbook/pbexchagegroup/list'),
          method: 'post',
          data: this.$http.adornData({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'keyword': this.dataForm.keyword
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 上下架
      onOroffHandle (id, status) {
        this.$confirm(`确定[${status === 1 ? '下架' : '上架'}]?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/picbook/pbexchagegroup/update'),
            method: 'post',
            data: {
              "pbExchageGroup": {
                "id": id,
                "status": status === 1 ? 0 : 1
              }
            }
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 下载
      downloadHandle (id) {
        // var list = []
        // for(var i = 0; i < this.dataList.length; i++) {
        //   if(this.dataList[i].id === id) {
        //     list = this.dataList[i]
        //   }
        // }
        // //要导出的json数据
        // var jsonData = [
        //   {
        //     name: list.name,
        //     exchangeType: list.exchangeType,
        //     exchangeDays: list.exchangeDays,
        //     codeCount: list.codeCount,
        //     startTime: list.startTime,
        //     endTime: list.endTime,
        //     status: list.status
        //   }
        // ]
        // let str = `兑换活动名称,兑换类型,兑换天数,兑换码总数,兑换券生效时间,兑换券失效时间,状态\n`;
        // //增加\t为了不让表格显示科学计数法或者其他格式
        // for(let i = 0 ; i < jsonData.length ; i++ ){
        //   for(let item in jsonData[i]){
        //       str+=`${jsonData[i][item] + '\t'},`;     
        //   }
        //   str+='\n';
        // }
        // //encodeURIComponent解决中文乱码
        // let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
        // //通过创建a标签实现
        // var link = document.createElement("a");
        // link.href = uri;
        // //对下载的文件命名
        // link.download =  "兑换码.csv";
        // document.body.appendChild(link);
        // link.click();
        // document.body.removeChild(link);
        const token = this.getCookie("token")
        window.location = this.$http.adornUrl(`/picbook/pbexchagegroup/downloadList/${id}?token=${token}`)
        
      },
      // 获取token值
       getCookie(c_name){
         let c_start = null
         let  c_end = null
        if (document.cookie.length>0){//判断cookie是否存在
          //获取cookie名称加=的索引值
          c_start = document.cookie.indexOf(c_name + "=");
          if (c_start!=-1){ //说明这个cookie存在
            //获取cookie名称对应值的开始索引值
            c_start = c_start + c_name.length+1 
            //从c_start位置开始找第一个分号的索引值，也就是cookie名称对应值的结束索引值
            c_end=document.cookie.indexOf(";",c_start)  
            //如果找不到，说明是cookie名称对应值的结束索引值就是cookie的长度
            if (c_end==-1) c_end=document.cookie.length 
            //unescape() 函数可对通过 escape() 编码的字符串进行解码
            //获取cookie名称对应的值，并返回
            return unescape(document.cookie.substring(c_start,c_end))
          } 
        }
        return "" //不存在返回空字符串
    },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        // this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        this.$confirm(`确定[${id ? '删除' : '批量删除'}]?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/picbook/pbexchagegroup/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }
    }
  }
</script>
